<!--
 @description dateTimePicker选择
 @fileName index.vue
 @author zengqiongying
 @created 2023/02/09 11:16:10
-->
<template>
  <div class="c-filed-picker">
    <van-field v-model="value" class="cus-field" label="" left-icon="calendar-o" readonly placeholder="选择年月" @click.native="openYearMonth" />

    <van-popup v-model="showDate" position="bottom">
      <van-datetime-picker
        v-model="currentDate"
        title=""
        :type="type"
        :min-date="minDate"
        :max-date="maxDate"
        :formatter="formatter"
        @change="changePicker"
        @confirm="confirmPicker"
        @cancel="cancelPicker"
      />
    </van-popup>
  </div>
</template>

<script>
import { parseTime } from '@/utils'
export default {
  name: 'FieldDateTime',
  props: {
    value: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: '请选择'
    },
    minDate: {
      type: Date,
      default: null
    },
    maxDate: {
      type: Date,
      default: null
    },
    type: {
      type: String,
      default: 'year-month' // 时间类型，可选值为 date time year-month month-day datehour
    }

  },
  data() {
    return {
      currentDate: '',
      showDate: false
    }
  },

  computed: {},
  watch: {
    value: {
      handler(val) {
        if (val) {
          const d = parseTime(`${val}-01`, '{y}-{m}-{d}')
          this.currentDate = new Date(d)
        } else {
          this.currentDate = new Date()
        }
      },
      immediate: true
    }
  },

  created() {},
  activated() {},

  mounted() {},

  methods: {
    formatter(type, val) {
      if (this.type === 'year-month') {
        if (type === 'year') {
          return `${val}年`
        } else if (type === 'month') {
          return `${val}月`
        }
      }
      return val
    },
    openYearMonth() {
      this.showDate = true
    },

    changePicker(picker) {

    },
    cancelPicker() {

    },
    confirmPicker(time) {
      const year = time.getFullYear()
      const month = time.getMonth() + 1
      const day = time.getDate()
      this.$emit('input', `${year}-${month < 10 ? '0' + month : month}`)
      this.showDate = false
    }
  }
}

</script>
<style lang='scss' scoped>
</style>
